package android.slc.appdb.sys.service.imp;

import android.slc.appdb.sys.entity.CsDictData;
import android.slc.appdb.sys.enums.StateEnum;
import android.slc.appdb.sys.service.CsDictDataMapper;
import android.slc.appdb.utils.DictEnumUtils;
import android.slc.box.db.service.impl.DbEntityMapperImpl;
import cn.hutool.core.util.IdUtil;
import io.reactivex.rxjava3.annotations.NonNull;
import org.apache.commons.lang3.StringUtils;

import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @Description:
 * @Author: sunlunchang
 * @CreateDate: 2021/8/13 14:29
 */
public class CsDictDataMapperImp extends DbEntityMapperImpl<CsDictData> implements CsDictDataMapper {
    public CsDictDataMapperImp() {
        super("dictData");
    }

    public CsDictDataMapperImp(String dbName) {
        super(dbName, "dictData");
    }


    @Override
    public void checkEntity(CsDictData entity) {
        super.checkEntity(entity);
        if (entity.getDictCode() == null) {
            entity.setDictCode(IdUtil.getSnowflakeNextId());
        }
        CsDictData csDictData = findDictDataByDictType(entity.getDictType(), entity.getDictValue());
        if (csDictData != null) {
            if (!Objects.equals(entity.getDictCode(), csDictData.getDictCode())) {
                throw new RuntimeException("字典类型" + entity.getDictType() + "下已存在字典值" + csDictData.getDictValue() + "!");
            }
        }
        /*if (csDictData != null && csDictData.getDictCode() != null) {
            entity.setDictCode(csDictData.getDictCode());
        }*/
        entity.setStatusName(DictEnumUtils.getLabelByValue(StateEnum.values(), entity.get_status()));
    }

    @Override
    public CsDictData findDictDataByDictType(@NonNull String dictType, @NonNull String dictValue) {
        return getOne((targetData, queryCondition) -> StringUtils.equals(targetData.getDictType(), dictType) && StringUtils.equals(targetData.getDictValue(), dictValue));
    }

    @Override
    public List<CsDictData> findDictDataListByDictType(@NonNull String dictType) {
        return select((targetData, queryCondition) -> StringUtils.equals(targetData.getDictType(), dictType));
    }

    @Override
    public Map<String, CsDictData> getAllPrivate() {
        Map<String, CsDictData> map = super.getAllPrivate();
        map.forEach((s, csDictData) -> csDictData.setStatusName(DictEnumUtils.getLabelByValue(StateEnum.values(), csDictData.get_status())));
        return map;
    }
}
